package com.xiaobias.controller;

import com.xiaobias.utils.FileUtils;
import com.xiaobias.utils.Java2Smali;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.*;

@Controller
public class JavaToaSmaliController {

    private final static Logger logger = LoggerFactory.getLogger(JavaToaSmaliController.class);


    @PostMapping("/api/toSmali")
    @ResponseBody
    public String toSmali(@RequestParam(defaultValue = "", required = false) String fileName, @RequestParam(defaultValue = "", required = false) String content) {
        try {
            fileName = Java2Smali.JAVA_PATH + fileName + ".java";
            FileUtils.createFile(fileName);
            IOUtils.write(content.getBytes(StandardCharsets.UTF_8), new FileOutputStream(fileName));
            byte[] smaliByJavaSource = getSmaliByJavaSource();
            return new String(smaliByJavaSource);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    @RequestMapping(value="/upload" , method = RequestMethod.POST)
    @ResponseBody
    public String uploadSource(@RequestParam("file") MultipartFile file , HttpServletRequest request) {
        System.out.println(file);
        String pathString = null;
        if(file!=null) {
            pathString = Java2Smali.JAVA_PATH + file.getOriginalFilename();
        }

        try {
            assert pathString != null;
            File files = new File(pathString);
            if(!files.getParentFile().exists()){
                files.getParentFile().mkdirs();
            }
            file.transferTo(files);

        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        }

        return "{\"code\":0,\"msg\":\"请点击提交！\"}";
    }

    @GetMapping
    public String javaToSmali() {
        return "javaToSmali";
    }

    @ResponseBody
    @RequestMapping(method = {RequestMethod.POST}, value = {"getSmaliByJavaSource"})
    public byte[] getSmaliByJavaSource() {
        byte[] bytes = new byte[0];
        try {
            Java2Smali.compileJava2Smali();
            List<String> file = getFile(new File(Java2Smali.SMALI_PATH), new ArrayList<>());
            if (file.size() == 0) {
                logger.warn("编译失败！");

                FileUtils.forceDelete(new File(Java2Smali.SMALI_PATH));
                FileUtils.forceDelete(new File(Java2Smali.JAVA_PATH));
                FileUtils.forceDelete(new File(Java2Smali.CLASS_PATH));

                return null;
            }
            bytes = FileUtils.readFileToByteArray(new File(file.get(file.size() - 1)));

            FileUtils.forceDelete(new File(Java2Smali.SMALI_PATH));
            FileUtils.forceDelete(new File(Java2Smali.JAVA_PATH));
            FileUtils.forceDelete(new File(Java2Smali.CLASS_PATH));
        } catch (IOException e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        return bytes;
    }

    private List<String> getFile(File file, List<String> resultFileName){
        try {
            File[] files = file.listFiles();
            if(files==null)return resultFileName;// 判断目录下是不是空的
            for (File f : files) {
                if(f.isDirectory()){// 判断是否文件夹
                    resultFileName.add(f.getPath());
                    getFile(f,resultFileName);// 调用自身,查找子目录
                }else
                    resultFileName.add(f.getPath());
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        return resultFileName;
    }

}